<template>
  <div class="system-user-manage">
    <div class="page-header">
      <h2>系统用户管理</h2>
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon>
        新增系统用户
      </el-button>
    </div>
    
    <el-card>
      <template #header>
        <div class="table-header">
          <span>系统用户列表</span>
          <div class="header-actions">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索用户名或邮箱"
              style="width: 200px; margin-right: 10px;"
              clearable
            />
            <el-button @click="handleSearch">搜索</el-button>
            <el-button @click="handleReset">重置</el-button>
          </div>
        </div>
      </template>
      
      <el-table :data="userList" v-loading="loading">
        <el-table-column type="index" label="序号" width="60" />
        <el-table-column prop="username" label="用户名" width="120" />
        <el-table-column prop="email" label="邮箱" min-width="150" />
        <el-table-column prop="roles" label="角色" width="120">
          <template #default="scope">
            <div class="role-tags">
              <el-tag 
                v-for="role in scope.row.roles" 
                :key="role.id"
                :type="getRoleType(role.name)"
                size="small"
                style="margin-right: 4px; margin-bottom: 4px;"
              >
                {{ role.name }}
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'danger'">
              {{ scope.row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="lastLogin" label="最后登录" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.lastLogin) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status ? 'warning' : 'success'"
              @click="handleToggleStatus(scope.row)"
            >
              {{ scope.row.status ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger"
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 系统用户编辑对话框 -->
    <el-dialog
      v-model="userDialogVisible"
      :title="userDialogTitle"
      width="600px"
    >
      <el-form :model="userForm" label-width="80px">
        <el-form-item label="用户名" required>
          <el-input v-model="userForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="邮箱" required>
          <el-input v-model="userForm.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item :label="userForm.id ? '新密码' : '密码'" required>
          <el-input 
            v-model="userForm.password" 
            type="password" 
            :placeholder="userForm.id ? '留空则不修改密码' : '请输入密码'" 
          />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="userForm.roleIds" multiple placeholder="请选择角色" style="width: 100%;">
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="userForm.status" active-text="启用" inactive-text="禁用" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="userDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleUserSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { systemUserService } from '../../services/systemUserService'
import { permissionService } from '../../services/permissionService'
import { useAuthStore } from '../../stores/auth'

const authStore = useAuthStore()

const loading = ref(false)
const searchKeyword = ref('')
const userList = ref([])
const userDialogVisible = ref(false)
const userDialogTitle = ref('')
const roleList = ref([])

const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

const userForm = ref({
  id: null,
  username: '',
  email: '',
  password: '',
  status: true,
  roleIds: []
})

const getRoleType = (role) => {
  const roleMap = {
    admin: 'danger',
    editor: 'warning',
    user: 'info'
  }
  return roleMap[role] || 'info'
}

const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 加载系统用户列表
const loadUserList = async () => {
  try {
    loading.value = true
    const params = {
      page: pagination.current - 1,  // 后端页码从0开始
      size: pagination.size,
      keyword: searchKeyword.value
    }
    
    const response = await systemUserService.getSystemUserList(params)
    const { data } = response
    
    // 后端返回分页对象
    userList.value = data?.content || []
    pagination.total = data?.totalElements || 0
  } catch (error) {
    console.error('加载系统用户列表失败:', error)
    ElMessage.error('加载系统用户列表失败')
  } finally {
    loading.value = false
  }
}

const handleSearch = () => {
  pagination.current = 1
  loadUserList()
}

const handleReset = () => {
  searchKeyword.value = ''
  pagination.current = 1
  loadUserList()
}

const handleCreate = () => {
  // 打开创建系统用户对话框
  userForm.value = {
    username: '',
    email: '',
    password: '',
    status: true,
    roleIds: []
  }
  userDialogTitle.value = '新增系统用户'
  userDialogVisible.value = true
}

const handleEdit = (row) => {
  // 打开编辑系统用户对话框
  userForm.value = {
    id: row.id,
    username: row.username,
    email: row.email,
    password: '',
    status: row.status,
    roleIds: row.roles?.map(role => role.id) || []
  }
  userDialogTitle.value = '编辑系统用户'
  userDialogVisible.value = true
}

const handleToggleStatus = async (row) => {
  try {
    const action = row.status ? '禁用' : '启用'
    await ElMessageBox.confirm(
      `确定要${action}系统用户 "${row.username}" 吗？`,
      `${action}确认`,
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用API更新系统用户状态
    await systemUserService.toggleSystemUserStatus(row.id)
    ElMessage.success(`${action}成功`)
    loadUserList() // 重新加载列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('更新系统用户状态失败:', error)
      ElMessage.error(`${action}失败`)
    }
  }
}

const handleDelete = async (row) => {
  try {
    // 检查是否为当前登录用户
    const currentUser = authStore.user
  
    // 添加空值检查和字段验证
    if (!currentUser || !currentUser.userId) {
      console.warn('无法获取当前用户信息')
      return
    }
    
    // 使用严格比较，确保类型一致
    if (currentUser.userId === row.id) {
      ElMessage.warning('不能删除当前登录的用户')
      return
    }
    
    await ElMessageBox.confirm(
      `确定要删除系统用户 "${row.username}" 吗？此操作不可恢复。`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // 调用API删除系统用户
    await systemUserService.deleteSystemUser(row.id)
    ElMessage.success('删除系统用户成功')
    loadUserList() // 重新加载列表
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除系统用户失败:', error)
      ElMessage.error('删除系统用户失败')
    }
  }
}

const handleSizeChange = (size) => {
  pagination.size = size
  pagination.current = 1
  loadUserList()
}

const handleCurrentChange = (current) => {
  pagination.current = current
  loadUserList()
}

// 加载角色列表
const loadRoleList = async () => {
  try {
    const response = await permissionService.getRoleList({
      page: 0,
      size: 100
    })
    roleList.value = response.data?.content || []
  } catch (error) {
    console.error('加载角色列表失败:', error)
    ElMessage.error('加载角色列表失败')
  }
}

// 提交系统用户表单
const handleUserSubmit = async () => {
  try {
    if (userForm.value.id) {
      // 编辑系统用户
      await systemUserService.updateSystemUser(userForm.value.id, userForm.value)
      ElMessage.success('系统用户更新成功')
    } else {
      // 创建系统用户
      await systemUserService.createSystemUser(userForm.value)
      ElMessage.success('系统用户创建成功')
    }
    
    userDialogVisible.value = false
    loadUserList() // 重新加载列表
  } catch (error) {
    console.error('保存系统用户失败:', error)
    ElMessage.error('保存系统用户失败')
  }
}

onMounted(() => {
  loadUserList()
  loadRoleList()
})
</script>

<style scoped>
.system-user-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
  color: #333;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.role-tags {
  display: flex;
  flex-wrap: wrap;
}
</style>